package edu.gatech.stolen.tea.display.item;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import edu.gatech.stolen.tea.Accounts;
import edu.gatech.stolen.tea.ItemEditor;
import edu.gatech.stolen.tea.R;
import edu.gatech.stolen.tea.ToDoItem;
import edu.gatech.stolen.tea.R.id;
import edu.gatech.stolen.tea.R.layout;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class CreateItemActivity extends Activity {
	
	public static final String TAG = "Create Item Page";
	
	private EditText name;
	private EditText description;
	private EditText location;
	private Button creButton;
	private Button canButton;
	private TextView createInfo;
	private Accounts accounts= new Accounts();
	private Spinner category;
	private String categoryS;
    private TextView dateGivenDisplay;
    private Button dateGivenbutton;
    private int dateGivenYear;
    private int dateGivenMonth;
    private int dateGivenDay;
    private TextView dateDueDisplay;
    private Button dateDuebutton;
    private int dateDueYear;
    private int dateDueMonth;
    private int dateDueDay;
    private TextView timeDueDisplay;
    private Button timeDuebutton;
    private int timeDueHour;
    private int timeDueMin;
    static final int DATE_Given_DIALOG_ID = 0;
    static final int DATE_Due_DIALOG_ID = 1;	
    static final int TIME_DUE_DIALOG_ID=2;
	
    /** Called when the activity is first created.
     * initialize the buttons and text fields
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
    	Log.v(TAG, "Activity State: onCreate()");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.createitem);
        accounts=accounts.loadData(getFilesDir().toString());
        //date picker
        dateGivenDisplay = (TextView) findViewById(R.id.dateGivenView);
        dateGivenbutton = (Button) findViewById(R.id.dateGivenChanger);
        // add a click listener to the button
        dateGivenbutton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(DATE_Given_DIALOG_ID);
            }
        });
        dateDueDisplay = (TextView) findViewById(R.id.dateDueView);
        dateDuebutton = (Button) findViewById(R.id.dateDueChanger);
        // add a click listener to the button
        dateDuebutton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(DATE_Due_DIALOG_ID);
            }
        });
        timeDueDisplay = (TextView) findViewById(R.id.timeDueDisplay);
        timeDuebutton = (Button) findViewById(R.id.timeDueChanger);
        // add a click listener to the button
        timeDuebutton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(TIME_DUE_DIALOG_ID);
            }
        });
        // get the current date
        final Calendar c = Calendar.getInstance();
        dateGivenYear = c.get(Calendar.YEAR);
        dateGivenMonth = c.get(Calendar.MONTH);
        dateGivenDay = c.get(Calendar.DAY_OF_MONTH);
        dateDueYear = c.get(Calendar.YEAR);
        dateDueMonth = c.get(Calendar.MONTH);
        dateDueDay = c.get(Calendar.DAY_OF_MONTH);
        timeDueHour = c.get(Calendar.HOUR_OF_DAY);
        timeDueMin = c.get(Calendar.MINUTE);
        // display the current date (this method is below)
        updateDisplay();
        
        name = (EditText) findViewById(R.id.eNameEditText_createitem);
        description = (EditText) findViewById(R.id.eDescriptionEditText_createitem);
        category = (Spinner) findViewById(R.id.category_spinner);
        ArrayAdapter<CharSequence> category_adapter = 
	    	ArrayAdapter.createFromResource(this, R.array.categories_array, 
	    			android.R.layout.simple_spinner_item);
        category_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        category.setAdapter(category_adapter);
        category.setOnItemSelectedListener(new MyOnItemSelectedListener());
        location = (EditText) findViewById(R.id.eLocationEditText_createitem);
        creButton = (Button) findViewById(R.id.bCreateButton_createitem);
        canButton = (Button) findViewById(R.id.bCancelButton_createitem);
        createInfo = (TextView) findViewById(R.id.lblCreateInfo);
       
    	
        /**
         * give register button a click listener
         */
        creButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				onCreButtonClicked();
				
			}
        });
        
        /**
         * give cancel button a register listener
         */
        canButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				onCanButtonClicked();
				
			}
        });
        
       
        
    	
    }
    // updates the date in the TextView
    private void updateDisplay() {
        dateGivenDisplay.setText(
            new StringBuilder()
                    // Month is 0 based so add 1
                    .append(dateGivenMonth + 1).append("/")
                    .append(dateGivenDay).append("/")
                    .append(dateGivenYear).append(" "));
        dateDueDisplay.setText(
                new StringBuilder()
                        // Month is 0 based so add 1
                        .append(dateDueMonth + 1).append("/")
                        .append(dateDueDay).append("/")
                        .append(dateDueYear).append(" "));
        timeDueDisplay.setText(
                new StringBuilder()
                        .append(pad(timeDueHour)).append(":")
                        .append(pad(timeDueMin)));
        
    }
    private static String pad(int c) {
        if (c >= 10)
            return String.valueOf(c);
        else
            return "0" + String.valueOf(c);
    }
    // the callback received when the user "sets" the date in the dialog
    private DatePickerDialog.OnDateSetListener DateDueSetListener =
            new DatePickerDialog.OnDateSetListener() {

                public void onDateSet(DatePicker view, int year, 
                                      int monthOfYear, int dayOfMonth) {
                    dateDueYear = year;
                    dateDueMonth = monthOfYear;
                    dateDueDay = dayOfMonth;
                    updateDisplay();
                }

            };
            private DatePickerDialog.OnDateSetListener DateGivenSetListener =
                new DatePickerDialog.OnDateSetListener() {

                    public void onDateSet(DatePicker view, int year, 
                                          int monthOfYear, int dayOfMonth) {
                        dateGivenYear = year;
                        dateGivenMonth = monthOfYear;
                        dateGivenDay = dayOfMonth;
                        updateDisplay();
                    }

                };
             // the callback received when the user "sets" the time in the dialog
                private TimePickerDialog.OnTimeSetListener mTimeSetListener =
                    new TimePickerDialog.OnTimeSetListener() {
                        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                            timeDueHour = hourOfDay;
                            timeDueMin = minute;
                            updateDisplay();
                        }
                    };
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DATE_Given_DIALOG_ID:
            return new DatePickerDialog(this,
                        DateGivenSetListener,
                        dateGivenYear, dateGivenMonth, dateGivenDay);
        case DATE_Due_DIALOG_ID:
            return new DatePickerDialog(this,
                        DateDueSetListener,
                        dateDueYear, dateDueMonth, dateDueDay);
        case TIME_DUE_DIALOG_ID:
            return new TimePickerDialog(this,
                    mTimeSetListener, timeDueHour, timeDueMin, false);
        }
        return null;
    }
	/**
     * if creation fails, notify the user
     * if creation successful, go to item display page
     */
    private void onCreButtonClicked() {
    	
    	Log.v(TAG, "Register Button Clicked");
    	int flag = createNewItem();
    	if(flag == 2){
    		goToItemDisplayListPage();
    	} else {
    		if(flag == 0){
    			createInfo.setText("Creation failed. Please fill in all blanks.");
    		} else {
    			createInfo.setText("Creation failed. Item already exists.");
    		}
    		
    	}
    	
    }
    
    /**
     * if cancel button clicked, go back to display page
     */
    private void onCanButtonClicked() {
    	
    	Log.v(TAG, "Cancel Button Clicked");
    	goToItemDisplayListPage();
    	
    }
    
    /**
     * create a new item
     * @return true if creation successfully, false if otherwise
     */
    private int createNewItem() {
    	
    	String n = name.getText().toString();
    	String d = description.getText().toString();
    	String l = location.getText().toString();
    	String dD = dateDueDisplay.getText().toString()+timeDueDisplay.getText().toString();
    	Log.v(TAG, dD);
    	String c = categoryS;
    	
    	if( n.equals("") || d.equals("") || l.equals("")){
    		return 0;
    	} else {
	    	ToDoItem newItem = new ToDoItem();
	    	newItem.setCategory(c);
	    	newItem.setDescription(d);
	    	newItem.setDueDate(dD);
	    	newItem.setName(n);
	    	newItem.setLocation(l);
	    	if(accounts.itemEditor.getItem(n) != null){
	    		return 1;
	    	} else {
	    		accounts.itemEditor.addItem(newItem);
	    		accounts.saveData(getFilesDir().toString());
	    		return 2;
	    	}
	    	
    	}
    	
    }
    
    /**
     * go to item display page
     */
    protected void goToItemDisplayListPage() {
    	
    	Intent i = new Intent(this, ItemDisplayListActivity.class);
    	startActivity(i);
   	
    } 
    
   
    
    /**
     * a item select listener for category spinner
     * @author Leshi
     *
     */
	public class MyOnItemSelectedListener implements OnItemSelectedListener {

	    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
	    	switch (parent.getId()) {
			case R.id.category_spinner:
				categoryS =parent.getItemAtPosition(pos).toString();
				break;
			


			default:
				break;
			}
	    	
	    }

	    public void onNothingSelected(AdapterView parent) {
	      // Do nothing.
	    }
	}

}